import React, { useState, useEffect } from "react";
import axios from "axios";
import dayjs from "dayjs";
import { UploadOutlined } from "@ant-design/icons";
import {
  Collapse,
  Divider,
  Flex,
  Tag,
  Button,
  Modal,
  Input,
  Table,
  Form,
  Space,
  InputNumber,
  Select,
  DateSelect,
  Col,
  Row,
  theme,
  message,
  DatePicker,
  Radio,
  Upload,
} from "antd";
import {
  getMsg,
  addMsg,
  getOrderList,
  dictType,
  getOrderDetail,
  processSave,
  repairSave,
  orderRemove,
  handleUpdate,
  orderDone,
  logisticsSave,
  employeeUserList,
  excelExport,
  createQrCode,
  employeeUserListAll,
  getQrcodeList,
  fixQrcode,
  genProductTime,
  excelTemplate,
  excelImport,
  provinceList,
} from "@/api";
import QRCodeWithCaption from "./components/utils";
import QRCode from "qrcode.react";
import { getToken } from "@/utils";
import moment from "moment";
import { DownOutlined } from "@ant-design/icons";
import { render } from "react-dom";
import { saveAs } from "file-saver";
import downloadImagesAsZip from "./components/moreExport";
import { debounce } from "lodash";

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

export default function SearchPage() {
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [form3] = Form.useForm();
  const [form4] = Form.useForm();
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);

  const [dialogData, setDialogData] = useState([]);

  const [modal, contextHolder] = Modal.useModal();

  const [open, setOpen] = useState(false);

  const [confirmLoading, setConfirmLoading] = useState(false);

  const [formValue, setFormVlaue] = useState({});

  const [selectRows, setSelectedRows] = useState([]);

  const [load, setLoad] = useState(true);
  const [total, setTotal] = useState(0);
  // const [showModal, setShow] = useState(false);

  const [tableData, setTableData] = useState<any>({
    list: [],
    total: 0,
    pageNumber: 1,
    pageSize: 10,
  });

  const [campanyData1, setCampanyData1] = useState([]);

  const [companyList, setCampanyData] = useState([]);

  const [clothData, setClothData] = useState([]);

  const [subTable, setSubTable] = useState({});

  const [selectRecord, setSelectRecord] = useState({}); // 二维码选择项

  // const [provinceCity, setProvinceCity] = useState('');

  // setOpen1(true);
  // setTitle("生产进度");
  // setModalData(r?.value?.logisticsList);

  const [open1, setOpen1] = useState(false);
  const [open2, setOpen2] = useState(false);
  const [open3, setOpen3] = useState(false);
  const [open4, setOpen4] = useState(false);

  const [title, setTitle] = useState("");
  const [modalData, setModalData] = useState([]);
  const [selectedRecord, setSelectedRecord] = useState({});
  const [visible, setVisible] = useState(false);
  const [selectTemplate, setSelectTemplate] = useState(0);
  const [radioValue, setRadioValue] = useState(1);
  const [imgData, setImgData] = useState("");
  const [file, setFile] = useState();
  const [fileList, setFileList] = useState();
  const [personListData, setPersonList] = useState([]);

  useEffect(() => {
    getCampanyData("GS");
    // getCampanyData("FSLX");
    getEmployeeList();
    // const personList = employeeUserListAll(null)
    // personList.then(res => {
    //   if (res.status === 200) {
    //     setPersonList(res.data.map(res => {
    //       return { label: res.name, value: res.phone   };
    //     }))
    //   }
    // });
  }, []);

  const [downloadUrl, setDownloadUrl] = useState("");

  const handleDownloadClick = async (r) => {
    try {
      // 发送 GET 请求以获取文件流
      const response = await axios.get(`/api/order/getQrcodePreview/${r.id}`, {
        responseType: "blob",
      });

      // 创建 Blob 对象
      const blob = new Blob([response.data], {
        type: response.headers["content-type"],
      });

      // 创建 Object URL
      const url = URL.createObjectURL(blob);

      // 设置下载 URL
      setDownloadUrl({ url, orderNumber: r.orderNumber });
      setVisible(true);
    } catch (error) {
      console.error("Error downloading file:", error);
    }
  };

  const getCampanyData = (code) => {
    dictType({ categoryCode: code, pageNumber: 1, pageSize: 999 }).then(
      (data) => {
        if (data?.status) {
          if (code === "GS") {
            setCampanyData(
              data?.data?.records?.map((item) => {
                return { label: item.value, value: item.value };
              })
            );
          } else if (code === "FSLX") {
            const arr = data?.data?.records?.map((item) => {
              return { label: item.value, value: item.value };
            });
            setClothData(arr);
          } else if (code === "SFCS") {
            setCampanyData1(
              data?.data?.records?.map((item) => {
                return { label: item.value, value: item.value };
              })
            );
          }
        } else {
          message.error(data?.msg || data?.code || "请求错误");
        }
      }
    );
  };

  const fun = debounce((value) => {
    getData(value);
  }, 500);

  const getData = (val) => {
    const result = provinceList({ addr: val });
    result.then((res) => {
      if (res.status === 200) {
        setCampanyData1(
          res?.data?.map((data) => {
            return { label: data.addr, value: data.addr };
          })
        );
      } else {
        message.error(res.msg || "导入失败");
      }
    });
  };

  const [personList, setDataSource] = useState();

  // 获取人员列表
  const getEmployeeList = () => {
    employeeUserList({ pageNumber: 1, pageSize: 999 }).then((res) => {
      const { data, status, msg } = res;
      if (status) {
        const arr = data?.records.map((item) => {
          return {
            label: item.name,
            value: item.phone,
          };
        });
        console.log(arr, "arr");

        setDataSource(arr);
      } else {
        message.error(msg || "获取数据失败！");
      }
    });
  };

  const AdvancedSearchForm = (props) => {
    const { setFormVlaue } = props;
    const { token } = theme.useToken();
    const [expand, setExpand] = useState(false);

    const formStyle: React.CSSProperties = {
      maxWidth: "none",
      background: token.colorFillAlter,
      borderRadius: token.borderRadiusLG,
      padding: 24,
    };

    const getFields = () => {
      const count = expand ? 8 : 6;

      const children = [
        <Col span={8} key={1}>
          <Form.Item name={"companyName"} label={"公司"}>
            <Select showSearch options={companyList || []} />
          </Form.Item>
        </Col>,

        <Col span={8} key={2}>
          <Form.Item name={"orderNumber"} label={"订单编号"}>
            <Input />
          </Form.Item>
        </Col>,

        <Col span={8} key={4}>
          <Form.Item name={"customerName"} label={"客户姓名"}>
            <Input />
          </Form.Item>
        </Col>,

        <Col span={8} key={5}>
          <Form.Item name={"clothingType"} label={"服饰类型"}>
            <Select showSearch options={clothData} />
          </Form.Item>
        </Col>,
        <Col span={8} key={6}>
          <Form.Item name={"customerProvinceCity"} label={"省份城市"}>
            <Select
              onSearch={(v) => {
                if (!v) return;
                fun(v);
              }}
              showSearch
              allowClear
              options={campanyData1}
            />
          </Form.Item>
        </Col>,
        <Col span={8} key={7}>
          <Form.Item name={"orderStatus"} label={"订单状态"}>
            <Select
              options={[
                { label: "进行中", value: "进行中" },
                { label: "结单", value: "结单" },
              ]}
            />
          </Form.Item>
        </Col>,
        <Col span={8} key={8}>
          <Form.Item name={"optType"} label={"生产操作类型"}>
            <Select
              showSearch
              options={[
                { label: "做工", value: "work" },
                { label: "裁剪", value: "cut" },
                { label: "验收", value: "accept" },
              ]}
            />
          </Form.Item>
        </Col>,
        <Col span={8} key={9}>
          <Form.Item name={"optPhone"} label={"生产操作人员"}>
            <Select showSearch options={personList} />
          </Form.Item>
        </Col>,
        //    <Col span={8} key={10}>
        //    <Form.Item name={"optUser"} label={"操作人员手机号"}>
        //      <Select showSearch options={personList} />
        //    </Form.Item>
        //  </Col>,
        <Col span={8} key={11}>
          <Form.Item name={"scanTime"} label={"生产扫码时间"}>
            <RangePicker
              placeholder={["开始时间", "结束时间"]}
              format={"YYYY-MM-DD"}
            />
          </Form.Item>
        </Col>,
        <Col span={8} key={12}>
          <Form.Item name={"expectedDeliveryTime"} label={"预计交付时间"}>
            <RangePicker
              placeholder={["开始时间", "结束时间"]}
              format={"YYYY-MM-DD"}
            />
          </Form.Item>
        </Col>,
        <Col span={8} key={13}>
          <Form.Item name={"orderTime"} label={"下单时间"}>
            <RangePicker
              placeholder={["开始时间", "结束时间"]}
              format={"YYYY-MM-DD"}
            />
          </Form.Item>
        </Col>,
        // <Col span={8} key={13}>
        //   <Form.Item name={"ordertime"} label={"下单时间"}>
        //     <RangePicker
        //       placeholder={["开始时间", "结束时间"]}
        //       format={"YYYY-MM-DD"}
        //     />
        //   </Form.Item>
        // </Col>,
      ];

      return children;
    };

    const onFinish = (values: any) => {
      console.log("Received values of form: ", values);
      const {
        orderTime = [],
        expectedDeliveryTime = [],
        scanTime = [],
      } = values;
      const [orderTimeStart, orderTimeEnd] = orderTime;
      const [scanTimeStart, scanTimeEnd] = scanTime;
      const [expectedDeliveryTimeStart, expectedDeliveryTimeEnd] =
        expectedDeliveryTime;
      console.log(
        moment(scanTimeEnd?.valueOf()).format("YYYY-MM-DD HH:mm:ss"),
        "scanTimeEnd"
      );

      const formData = {
        ...values,
        orderTimeStart: orderTimeStart
          ? moment(orderTimeStart?.valueOf()).format("YYYY-MM-DD HH:mm:ss")
          : null,
        orderTimeEnd: orderTimeEnd
          ? moment(orderTimeEnd?.valueOf()).format("YYYY-MM-DD HH:mm:ss")
          : null,
        expectedDeliveryTimeStart: expectedDeliveryTimeStart
          ? moment(expectedDeliveryTimeStart?.valueOf()).format(
              "YYYY-MM-DD HH:mm:ss"
            )
          : null,
        expectedDeliveryTimeEnd: expectedDeliveryTimeEnd
          ? moment(expectedDeliveryTimeEnd?.valueOf()).format(
              "YYYY-MM-DD HH:mm:ss"
            )
          : null,
        scanTimeStart: scanTimeStart
          ? moment(scanTimeStart?.valueOf()).format("YYYY-MM-DD HH:mm:ss")
          : null,
        scanTimeEnd: scanTimeEnd
          ? moment(scanTimeEnd?.valueOf()).format("YYYY-MM-DD HH:mm:ss")
          : null,
      };
      delete formData.expectedDeliveryTime;
      delete formData.orderTime;
      delete formData.scanTime;

      setFormVlaue(formData);
    };

    return (
      <Form
        form={form}
        name="advanced_search"
        style={formStyle}
        onFinish={onFinish}
      >
        <Row gutter={24}>{getFields()}</Row>

        <div style={{ textAlign: "right" }}>
          <Space size="small">
            <Button type="primary" htmlType="submit">
              查询
            </Button>

            <Button
              onClick={() => {
                // setFormVlaue(form.getFieldsValue());

                form.resetFields();
                onFinish({});
              }}
            >
              重置
            </Button>
          </Space>
        </div>
      </Form>
    );
  };
  useEffect(() => {
    // const { pageNumber, pageSize } = tableData;
    // getDataList({ ...formValue, pageNumber, pageSize });
    updateTable();
  }, [formValue]);

  const columns = [
    {
      title: "订单编码",
      dataIndex: "orderNumber",
      // defaultSortOrder: "descend",
      fixed: 'left',
      width: 160,
    },
    {
      title: "公司",
      dataIndex: "companyName",
      width: 120,
      fixed: 'left',
    },

    {
      title: "下单时间",
      dataIndex: "orderTime",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "姓名",
      dataIndex: "customerName",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "年龄",
      dataIndex: "customerAge",
      defaultSortOrder: "descend",
      width: 100,
    },
    {
      title: "服饰类型",
      dataIndex: "clothingType",
      defaultSortOrder: "descend",
      width: 180,
    },

    {
      title: "规格型号",
      dataIndex: "specification",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "额外要求",
      dataIndex: "additionalRequirements",
      defaultSortOrder: "descend",
      width: 180,
    },
    {
      title: "数量",
      dataIndex: "quantity",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "预计交付时间",
      dataIndex: "expectedDeliveryTime",
      defaultSortOrder: "descend",
      width: 200,
    },
    {
      title: "单价",
      dataIndex: "unitPrice",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "金额",
      dataIndex: "totalAmount",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "收件地址",
      dataIndex: "customerAddress",
      defaultSortOrder: "descend",
      width: 180,
    },
    {
      title: "省份城市",
      dataIndex: "customerProvinceCity",
      defaultSortOrder: "descend",
      width: 180,
    },
    {
      title: "电话号码",
      dataIndex: "customerPhone",
      defaultSortOrder: "descend",
      width: 160,
    },
    {
      title: "排产时间",
      dataIndex: "productionTime",
      defaultSortOrder: "descend",
      width: 180,
    },
    {
      title: "订单状态",
      dataIndex: "orderStatus",
      width: 180,
    },
    {
      title: "操作",
      dataIndex: "id",
      width: 180,
      defaultSortOrder: "descend",
      fixed: "right",
      render: (v, r) => (
        <>
          {r.orderStatus !== "完结" && (
            <>
              {" "}
              <a onClick={() => showModal(r)}>编辑</a>
              &nbsp;
              <a
                onClick={() => {
                  // const res = createQrCode(r.orderNumber);
                  // res.then((result) => {
                  //   console.log(result, ";result");

                  //   if (result.code === 200) {
                  //     // console.log(result.msg);

                  //     setImgData(result.msg);
                  //   }
                  // });
                  handleDownloadClick(r);
                  // setVisible(true);
                  // setSelectRecord(r);
                }}
              >
                二维码
              </a>
            </>
          )}
          &nbsp;
          <a
            onClick={() => {
              Modal.warning({
                title: "删除",
                content: <>确认删除吗？删除后不可还原。</>,
                onOk(...args) {
                  orderRemove(v);
                  const { pageNumber, pageSize } = tableData;
                  setTimeout(() => {
                    getDataList({ ...formValue, pageNumber, pageSize });
                  }, 500);
                },
              });
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const columns2 = [
    {
      title: "操作类型",
      dataIndex: "type",

      // cell:
    },
    {
      title: "详细",
      dataIndex: "value",
      render: (v, r) => {
        switch (r.type) {
          case "生产进度":
            return (
              <a
                onClick={() => {
                  setOpen1(true);
                  setTitle("生产进度");
                  setModalData(r?.value?.productionProcessList);
                }}
              >{`详细 （共${r?.value?.productionProcessList?.length}条）`}</a>
            );
            break;
          case "返修信息":
            return (
              <a
                onClick={() => {
                  setOpen1(true);
                  setTitle("返修信息");
                  setModalData(r?.value?.repairList);
                }}
              >{`详细 （共${r?.value?.repairList?.length}条）`}</a>
            );
            break;
          case "物流信息":
            return (
              <a
                onClick={() => {
                  setOpen1(true);
                  setTitle("物流信息");
                  setModalData(r?.value?.logisticsList);
                }}
              >{`详细 （共${r?.value?.logisticsList?.length}条）`}</a>
            );
            break;

          default:
            break;
        }
      },
    },
  ];

  const columns3 = [
    {
      title: "订单号",
      dataIndex: "orderId",
    },
    {
      title: "操作时间",
      dataIndex: "orderId",
    },
    {
      title: "操作人员",
      dataIndex: "orderId",
    },
    {
      title: "备注",
      dataIndex: "orderId",
    },
  ];

  const objType = {
    work: "做工",
    cut: "裁剪",
    accept: "验收",
  };

  const columns4 = [
    {
      title: "订单号",
      dataIndex: "orderId",
      width: "160",
    },
    {
      title: "操作类型",
      dataIndex: "optType",
      width: "180",
      render: (v) => {
        console.log(v, "vvv");
        if (!v) return "-";

        return objType[v];
      },
    },
    {
      title: "操作人",
      dataIndex: "optUser",
      width: "160",
    },
    {
      title: "电话",
      dataIndex: "optPhone",
      width: "180",
    },
    {
      title: "扫码时间",
      dataIndex: "scanTime",
      width: "180",
    },
    {
      title: "价格",
      dataIndex: "price",
      width: "160",
    },
    {
      title: "备注",
      dataIndex: "remark",
      width: "200",
    },
    {
      title: "操作",
      dataIndex: "inspectionScanTime",
      width: "200",
      render: (v, r) => {
        return (
          <a
            onClick={() => {
              form1.setFieldsValue({
                price: r.price || 0,
              });
              return Modal.info({
                title: "编辑",
                // footer: false,
                content: (
                  <>
                    <Form
                      // {...layout}
                      form={form1}
                      name="control-hooks"
                      onFinish={onFinish1}
                      style={{ maxWidth: 600 }}
                    >
                      <Form.Item
                        name="price"
                        label="价格"
                        // rules={[{ required: true }]}
                      >
                        <InputNumber min={0} />
                      </Form.Item>
                    </Form>
                  </>
                ),
                onOk(...args) {
                  processSave({
                    ...form1.getFieldsValue(),
                    orderId: r.orderId,
                    id: r.id,
                  });
                  setTimeout(() => {
                    handleClose();
                    setOpen1(false);
                  }, 500);
                },
                onCancel() {
                  console.log("cancel");
                },
              });
            }}
          >
            价格编辑
          </a>
        );
      },
    },
  ];

  const columns5 = [
    {
      title: "订单号",
      dataIndex: "orderId",
    },
    {
      title: "返修次数",
      dataIndex: "orderId",
    },
    {
      title: "返修人名称",
      dataIndex: "staffName",
    },
    {
      title: "返修人电话",
      dataIndex: "staffPhone",
    },
    {
      title: "返修扫码时间",
      dataIndex: "scanTime",
    },
    {
      title: "返修价格",
      dataIndex: "repairPrice",
    },
    {
      title: "操作",
      dataIndex: "inspectionScanTime",
      render: (v, r) => {
        console.log(r.repairPrice, "rrr");

        return (
          <a
            onClick={() => {
              form2.setFieldsValue({
                repairPrice: r.repairPrice || 0,
              });
              Modal.info({
                title: "编辑",
                // footer: false,
                content: (
                  <>
                    <Form
                      // {...layout}
                      form={form2}
                      name="control-hooks"
                      onFinish={onFinish1}
                      style={{ maxWidth: 600 }}
                    >
                      <Form.Item
                        name="repairPrice"
                        label="返修价格"
                        // rules={[{ required: true }]}
                      >
                        <InputNumber min={0} />
                      </Form.Item>
                    </Form>
                  </>
                ),
                onOk(...args) {
                  repairSave({
                    ...form2.getFieldsValue(),
                    id: r.id,
                    orderId: r.orderId,
                  });

                  setTimeout(() => {
                    updateTable();
                  }, 500);
                },
                onCancel() {
                  console.log("cancel");
                },
              });
            }}
          >
            价格编辑
          </a>
        );
      },
    },
  ];

  const columns6 = [
    {
      title: "订单号",
      dataIndex: "orderId",
    },
    {
      title: "发货扫码时间",
      dataIndex: "shippingScanTime",
    },
    {
      title: "发货人名称",
      dataIndex: "shippingStaffName",
    },
    {
      title: "发货人电话",
      dataIndex: "shippingStaffPhone",
    },
    {
      title: "快递公司",
      dataIndex: "courierCompany",
    },
    {
      title: "快递单号",
      dataIndex: "trackingNumber",
    },
    // {
    //   title: "操作",
    //   dataIndex: "inspectionScanTime",
    //   render: (v, r) => {
    //     form4.setFieldsValue({
    //       shippingStaffName: r.shippingStaffName,
    //       trackingNumber:r.trackingNumber
    //     });
    //     return (
    //       <a
    //         onClick={() => {
    //           Modal.info({
    //             title: "编辑",
    //             // footer: false,
    //             content: (
    //               <>
    //                 <Form
    //                   // {...layout}
    //                   form={form4}
    //                   name="control-hooks"
    //                   onFinish={onFinish1}
    //                   style={{ maxWidth: 600 }}
    //                 >
    //                   <Form.Item
    //                     name="shippingStaffName"
    //                     label="快递公司"
    //                     // rules={[{ required: true }]}
    //                   >
    //                     <Input  />
    //                   </Form.Item>
    //                   <Form.Item
    //                     name="trackingNumber"
    //                     label="快递单号"
    //                     // rules={[{ required: true }]}
    //                   >
    //                     <Input  />
    //                   </Form.Item>
    //                 </Form>
    //               </>
    //             ),
    //             onOk(...args) {
    //               logisticsSave({ ...form4.getFieldsValue(), id: r.id ,orderId:r.orderId});

    //               setTimeout(() => {
    //                 updateTable();
    //                 setOpen1(false)
    //               }, 500);
    //             },
    //             onCancel() {
    //               console.log("cancel");
    //             },
    //           });
    //         }}
    //       >
    //         价格编辑
    //       </a>
    //     );
    //   },
    // },
  ];

  const obj = {
    生产进度: columns4,
    返修信息: columns5,
    物流信息: columns6,
  };

  const data = [
    {
      key: "1",
      name: "John Brown",
      age: 32,
      address: "New York No. 1 Lake Park",
      detailList: [
        {
          key: "2",
          name: "Jim Green",
          age: 42,
          address: "London No. 1 Lake Park",
        },
        {
          key: "3",
          name: "Joe Black",
          age: 32,
          address: "Sydney No. 1 Lake Park",
        },
      ],
    },
    {
      key: "2",
      name: "Jim Green",
      age: 42,
      address: "London No. 1 Lake Park",
      detailList: [
        {
          key: "2",
          name: "Jim Green",
          age: 42,
          address: "London No. 1 Lake Park",
        },
        {
          key: "3",
          name: "Joe Black",
          age: 32,
          address: "Sydney No. 1 Lake Park",
        },
      ],
    },
    {
      key: "3",
      name: "Joe Black",
      age: 32,
      address: "Sydney No. 1 Lake Park",
    },
  ];

  const onFinish1 = (values: any) => {
    console.log(values);
  };

  const onPageChange = (pageNumber, pageSize) => {
    console.log(pageNumber, pageSize);
    getDataList({ ...formValue, pageNumber, pageSize });
  };

  const expandedRowRender = (id) => {
    return (
      <Table
        columns={columns2}
        dataSource={[
          { type: "生产进度", value: subTable[id] },
          { type: "返修信息", value: subTable[id] },
          { type: "物流信息", value: subTable[id] },
        ]}
        // dataSource={[subTable[id] ]|| []}
        pagination={false}
      />
    );
  };

  const showModal = (r) => {
    setSelectedRecord(r);
    // form3.initialValues()
    dayjs("2024-01-01").valueOf();
    form3.setFieldsValue({
      ...r,
      expectedDeliveryTime: dayjs(r.expectedDeliveryTime).valueOf(),
    });
    setOpen(true);
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const handleOk = () => {
    // setModalText('The modal will be closed after two seconds');
    setConfirmLoading(true);
    setTimeout(() => {
      setOpen(false);
      setOpen1(false);
      setConfirmLoading(false);
      handleClose();
    }, 2000);
  };

  const handleOk1 = () => {
    // setModalText('The modal will be closed after two seconds');
    setOpen1(false);
    handleClose();
  };

  const [selectRowKey, setSelectRowKey] = useState([]);

  // 折叠表格
  const handleClose = () => {
    setSelectRowKey([]);
  };

  const [downloadLink, setDownloadLink] = useState(null);

  useEffect(() => {
    if (downloadLink) {
      const link = document.createElement("a");
      link.href = downloadLink;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      setDownloadLink(null); // 清除链接，防止重复触发
    }
  }, [downloadLink]);

  const downloadExcel = async () => {
    try {
      const response = await axios({
        url: "/api/order/excelExport",
        data: { ...formValue, exportType: selectTemplate }, // 请根据后端返回的数据格式来填充
        responseType: "blob", // 设置响应类型为 blob
      });

      // 使用 FileSaver.js 保存文件
      const blob = new Blob([response.data]);
      saveAs(blob, "data.xlsx"); // 'data.xlsx' 是下载后保存的文件名
    } catch (error) {
      console.error("Error downloading the Excel file:", error);
    }
  };

  // 导出确认
  const handleExportOk = () => {
    downloadExcel();
    // setModalText('The modal will be closed after two seconds');
    // setConfirmLoading(true);
    // setTimeout(() => {
    //   setOpen(false);
    //   setConfirmLoading(false);
    // }, 2000);
  };

  //   // 获取列表
  const getDataList = (data) => {
    console.log(data);

    getOrderList(data).then((res) => {
      const { data, status, msg } = res;
      console.log(status, data);

      if (status === 200 && data) {
        setTableData({
          list: data.records,
          total: data.totalRow,
          pageNumber: data.pageNumber,
          pageSize: data.pageSize,
        });

        setLoad(false);
        return;
      } else {
        message.error(`获取数据失败:${msg}`);
        setLoad(false);
        return;
      }
    });
  };

  // 子列表
  const getSubTable = (id) => {
    console.log(id, "id");

    getOrderDetail(id).then((res) => {
      const { data, status, msg } = res;
      console.log(status, data);

      if (status === 200 && data) {
        setSubTable({ ...subTable, [id]: data });

        setLoad(false);
        return;
      } else {
        message.error(`获取数据失败:${msg}`);
        setLoad(false);
        return;
      }
    });
  };

  const onChange1 = (e) => {
    console.log(e.target.detail);
    setFormVlaue(data);
    getDataList(data);
  };

  const updateTable = () => {
    const { pageNumber, pageSize } = tableData;
    setTimeout(() => {
      getDataList({ ...formValue, pageNumber, pageSize });
    }, 500);
  };

  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setSelectedRows(selectedRows);
    },
    getCheckboxProps: (record) => ({
      disabled: record.orderStatus === "完结", // Column configuration not to be checked
      name: record.name,
    }),
  };

  const submit = () => {
    // setVisible(true);
    try {
      form3?.validateFields().then((values) => {
        const { expectedDeliveryTime } = values;

        handleUpdate({
          ...values,
          expectedDeliveryTime: expectedDeliveryTime
            ? moment(expectedDeliveryTime?.valueOf()).format(
                "YYYY-MM-DD HH:mm:ss"
              )
            : null,
          orderTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        }).then((res) => {
          const { data, status, msg } = res;
          if (status === 200 && data) {
            form.resetFields();
            message.success(msg || "编辑成功");
            setOpen(false);
            // const { pageNumber, pageSize } = tableData;
            // getDataList({ ...formValue, pageNumber, pageSize });
            updateTable();
            onReset();
            return;
          } else {
            message.error(msg || "编辑失败");
          }
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

  const onReset = () => {
    setOpen(false);
    form3.resetFields();
  };

  // 函数来处理图片的加载和下载链接的创建
  const handleImageDownload = () => {
    const orderIds = selectRows.map((item, index) => item.id);
    console.log(orderIds);
    const result = getQrcodeList({ orderIds });
    console.log(result);
    let imgs = [];
    result.then((res) => {
      if (res.status === 200) {
        imgs = res.data.map((item) => {
          return {
            url: item.fullUrl,
            alt: item.orderNumber,
            text: item.orderNumber,
            key: item.id,
          };
        });

        downloadImagesAsZip(imgs);
      } else {
        message.error(res.msg || "获取二维码数据失败");
      }
    });
  };

  const [timeValue, setTimeValue] = useState("");

  const dateOnChange = (v) => {
    setTimeValue(v.valueOf());
  };

  const paichanshijian = () => {
    const orderIds = selectRows.map((item, index) => item.id);
    const result = genProductTime({
      orderIds,
      productTime: moment(timeValue).format("YYYY-MM-DD HH:mm:ss"),
    });
    let imgs = [];
    result.then((res) => {
      if (res.status === 200) {
        message.success("更新成功");
        updateTable();
        setOpen4(false);
      } else {
        message.error(res.msg || "更新失败");
      }
    });
  };

  const props = {
    beforeUpload: (file) => {
      setFile(file);
      return false;
    },
    onChange: (info) => {
      // console.log(info.fileList);
      setFileList(info.fileList);
    },
  };

  const downloadExcelTemplate = async () => {
    try {
      const response = await axios({
        url: "/api/order/excel-template",
        // data: { ...formValue, exportType: selectTemplate }, // 请根据后端返回的数据格式来填充
        responseType: "blob", // 设置响应类型为 blob
      });

      // 使用 FileSaver.js 保存文件
      const blob = new Blob([response.data]);
      saveAs(blob, "data.xlsx"); // 'data.xlsx' 是下载后保存的文件名
    } catch (error) {
      console.error("Error downloading the Excel file:", error);
    }
  };

  return (
    <>
      <AdvancedSearchForm setFormVlaue={setFormVlaue} />
      {/* <div> */}
      <Button
        // disabled={!selectRows.length}
        style={{ marginRight: 8 }}
        type="primary"
        onClick={() => {
          setOpen2(true);
        }}
      >
        导出
      </Button>
      <Button
        // disabled={!selectRows.length}
        style={{ marginRight: 8 }}
        type="primary"
        onClick={() => {
          setOpen3(true);
        }}
      >
        导入
      </Button>
      <Button
        disabled={!selectRows.length}
        type="default"
        style={{ marginRight: 8 }}
        onClick={() => {}}
      >
        结单
      </Button>
      <Button
        disabled={!selectRows.length}
        style={{ marginRight: 8 }}
        type="default"
        onClick={() => {
          Modal.warning({
            title: "批量导出二维码",
            content:
              "请确认是否要批量导出所选的二维码？导出过程较慢，请耐心等候",
            onOk(...args) {
              const result = fixQrcode();
              result.then((result) => {
                if (result.status === 200) {
                  handleImageDownload();
                } else {
                  message.error(`导出二维码失败：${result.msg}`);
                }
              });

              // handleClose();
            },
          });
        }}
      >
        批量导出二维码
      </Button>
      <Button
        disabled={!selectRows.length}
        style={{ marginRight: 8 }}
        type="default"
        onClick={() => {
          setOpen4(true);
        }}
      >
        排产时间
      </Button>

      {/* </div> */}
      <Table
        rowKey={"id"}
        scroll={{ x: 1500 }}
        columns={columns}
        dataSource={tableData.list || []}
        // onChange={onChange}
        showSorterTooltip={{ target: "sorter-icon" }}
        rowSelection={{
          type: "checkbox",
          ...rowSelection,
        }}
        expandable={{
          expandedRowKeys: selectRowKey,
          onExpandedRowsChange: (e) => {
            setSelectRowKey(e);
          },
          onExpand: (id, record) => getSubTable(record.id),
          expandedRowRender: (record) => expandedRowRender(record.id),
        }}
        pagination={{
          total: tableData.total,
          pageSize: tableData.pageSize,
          current: tableData.pageNumber,
          showSizeChanger : true,
          showTotal: (total, range) => `共${tableData.total}条数据`,
          onChange: (pageNumber, pageSize) =>
            onPageChange(pageNumber, pageSize),
        }}
      />
      <Modal
        title="编辑"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        okText={"确定"}
        cancelText={"取消"}
        footer={false}
        width={700}
        // preserve={false}
      >
        <Form
          {...layout}
          form={form3}
          name="control-hooks"
          // onFinish={onFinish}
          style={{ maxWidth: 600 }}
        >
          <Form.Item name="id" label="订单id">
            <Input disabled />
          </Form.Item>
          <Form.Item name="companyName" label="公司">
            <Select
              placeholder="请选择"
              // onChange={onGenderChange}
              showSearch
              allowClear
              options={companyList}
            />
          </Form.Item>
          <Form.Item
            name="orderNumber"
            label="订单编码"
            rules={[{ required: true }]}
          >
            <Input disabled placeholder="请输入" />
          </Form.Item>

          <Form.Item
            name="customerName"
            label="客户姓名"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item name="customerAge" label="客户年龄">
            <InputNumber style={{ width: "100%" }} min={0} defaultValue={0} />
          </Form.Item>
          <Form.Item
            name="customerPhone"
            label="客户电话"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            name="clothingType"
            label="服饰类型"
            // rules={[{ required: true }]}
          >
            <Select
              placeholder="请选择"
              // onChange={onGenderChange}
              showSearch
              allowClear
              options={clothData}
            />
          </Form.Item>
          <Form.Item
            name="specification"
            label="规格型号"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item name="quantity" label="数量">
            <InputNumber style={{ width: "100%" }} />
          </Form.Item>

          <Form.Item
            name="unitPrice"
            label="单价"
            // rules={[{ required: true }]}
          >
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>
          <Form.Item
            name="totalAmount"
            label="金额"
            // rules={[{ required: true }]}
          >
            <InputNumber style={{ width: "100%" }} min={0} />
          </Form.Item>
          <Form.Item
            label="预计交付时间"
            name="expectedDeliveryTime"
            valuePropName="fileList"
            // getValueFromEvent={normFile}
          >
            {/* <RangePicker /> */}
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item
            name="customerAddress"
            label="收件地址"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            name="customerProvinceCity"
            label="省份城市"
            // rules={[{ required: true }]}
          >
            <Select
              placeholder="请先输入后再选择"
              // onChange={onGenderChange}
              onSearch={(v) => {
                if (!v) return;
                fun(v);
              }}
              showSearch
              allowClear
              options={campanyData1}
            />
          </Form.Item>
          <Form.Item name="additionalRequirements" label="额外要求">
            <TextArea placeholder="请输入订单备注" rows={4} />
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Space>
              <Button type="primary" htmlType="submit" onClick={() => submit()}>
                确定
              </Button>
              <Button htmlType="button" onClick={onReset}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={title}
        open={open1}
        onOk={handleOk1}
        width={800}
        okText={"确定"}
        cancelText={"取消"}
        // confirmLoading={confirmLoading}
        onCancel={() => setOpen1(false)}
        // preserve={false}
      >
        <Table
          columns={obj[title]}
          dataSource={modalData || []}
          // dataSource={[subTable[id] ]|| []}
          pagination={false}
        />
      </Modal>

      <Modal
        // size="mini"
        title="二维码"
        open={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        okText="确认"
        cancelText="取消"
        // footer={false}
      >
        <div style={{ width: "100%", textAlign: "center" }}>
          {/* <img src={downloadUrl} alt="二维码" /> */}
          <QRCodeWithCaption
            imageUrl={downloadUrl.url}
            text={downloadUrl.orderNumber}
          />

          {/* <QRCode value={selectRecord.id} /> */}
          <p>订单新建成功，可右键保存二维码</p>
        </div>
      </Modal>

      <Modal
        title={"导出"}
        open={open2}
        onOk={handleExportOk}
        width={800}
        // confirmLoading={confirmLoading}
        onCancel={() => setOpen2(false)}
        onClose={() => setOpen2(false)}
        // preserve={false}
      >
        <>
          导出模板选择 ：{" "}
          <Select
            defaultValue={0}
            style={{ width: "200px" }}
            options={[
              { label: "基础", value: 0 },
              { label: "订单状态信息表", value: 1 },
              { label: "人员工资表", value: 2 },
            ]}
            onChange={(e) => {
              setSelectTemplate(e);
            }}
          />
          <br />
          <br />
          导出范围：
          <Radio.Group
            // defaultValue={1}
            value={radioValue}
            onChange={(e) => {
              console.log(e, "Radio.Group", e.target.value);
              setRadioValue(e.target.value);
            }}
          >
            <Radio value={1}>当前搜索条件下所有数据</Radio>
            {/* <Radio value={2}>勾选项</Radio> */}
          </Radio.Group>
        </>
      </Modal>

      <Modal
        // size="mini"
        title="导入"
        open={open3}
        onOk={() => {
          let formdata = new FormData();
          formdata.append("file", file);
          const result = excelImport(formdata);

          result.then((res) => {
            if (res.status === 200) {
              updateTable();
              setOpen3(false);
              setFile(null);
              setFileList([]);
            } else {
              message.error(res.msg || "导入失败");
            }
          });
        }}
        onCancel={() => {
          setOpen3(false);
          setFile(null);
          setFileList([]);
        }}
        okText="确认"
        cancelText="取消"
        // footer={false}
      >
        <div style={{ width: "100%", textAlign: "center" }}>
          <Button type="link" onClick={() => downloadExcelTemplate()}>
            模板下载
          </Button>
          <br />
          <br />
          <br />
          <Upload {...props} fileList={fileList}>
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </div>
      </Modal>

      <Modal
        // size="mini"
        title="批量修改排单时间"
        open={open4}
        onOk={() => paichanshijian()}
        onCancel={() => setOpen4(false)}
        okText="确认"
        cancelText="取消"
        // footer={false}
      >
        <div style={{ width: "100%", textAlign: "center" }}>
          <DatePicker
            showTime
            style={{ width: "100%" }}
            onChange={dateOnChange}
            format={"YYYY-MM-DD"}
          />
        </div>
      </Modal>
    </>
  );
}

SearchPage.route = {
  [MENU_PATH]: "/list/search",
};
